package rpc

import (
	"github.com/smallnest/rpcx/client"
	"round_game/common/tools"
	"time"
)

//CreateRPC return a new RPC bind with EtcdDefaultCreator
func CreateRPC(base, etcd string, initClients ...string) (*RPC, error) {
	c := EtcdDefaultCreator(base, etcd)
	return create(c, initClients...)
}

//MustCreateRPC create & return a new RPC, if error, panic
func MustCreateRPC(base, etcd string, initClients ...string) *RPC {
	r, err := CreateRPC(base, etcd, initClients...)
	if err != nil {
		panic(err)
	}
	return r
}

//CreateEtcdRPC return a new RPC bind with EtcdCreator
func CreateEtcdRPC(
	timeout time.Duration,
	failmode client.FailMode,
	selectmode client.SelectMode,
	base string,
	etcds []string,
	initClients ...string,
) (*RPC, error) {
	c := EtcdCreator(timeout, failmode, selectmode, base, etcds...)
	return create(c, initClients...)
}

func create(c clientCreator, initClients ...string) (*RPC, error) {
	r := New(c)
	_, err := r.ReplaceClients(initClients...)
	return r, err
}

func loadServiceConfig(path string) (data map[string]interface{}, err error) {
	data = make(map[string]interface{})
	err = tools.FileJSON(path, &data)
	if err != nil {
		return
	}
	services, ok := data["service"]
	if !ok {
		return
	}
	return services.(map[string]interface{}), nil
}

func DebugCreator(path string) (clientCreator, error) {
	services, err := loadServiceConfig(path)
	if err != nil {
		return nil, err
	}
	keys := []string{"RpcAddrPort", "TCPPort"}
	getter := func(name string) string {
		service, ok := services[name].(map[string]interface{})
		if !ok {
			return ""
		}
		for _, k := range keys {
			rawport, ok := service[k]
			if ok {
				return rawport.(string)
			}
		}
		return ""
	}
	return RawPeerDefaultCreator(getter), nil
}
